﻿using System;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;

namespace NCMIS.ServiceModel.Ra
{
    /// <summary>
    /// Represents a <see cref="System.ServiceModel.Dispatcher.IDispatchMessageFormatter"/> that deserialize
    /// request messages and serialize response messages in a service application using the
    /// <see cref="NCMIS.ServiceModel.Ra.XmlDeclarationMessage"/> message class.
    /// Source: http://shevaspace.spaces.live.com/blog/cns!FD9A0F1F8DD06954!2012.entry
    /// </summary>
    public class XmlDeclarationMessageFormatter : IDispatchMessageFormatter
    {
        private IDispatchMessageFormatter formatter;

        /// <summary>
        /// Initializes a new instance of the <see cref="NCMIS.ServiceModel.Ra.XmlDeclarationMessageFormatter"/> class.
        /// </summary>
        /// <param name="formatter">The <see cref="System.ServiceModel.Dispatcher.IDispatchMessageFormatter"/> object
        /// to base this instance on.</param>
        public XmlDeclarationMessageFormatter(IDispatchMessageFormatter formatter)
        {
            this.formatter = formatter;
        }

        /// <summary>
        /// Deserializes a message into an array of parameters.
        /// </summary>
        /// <param name="message">The incoming message.</param>
        /// <param name="parameters">The objects that are passed to the operation as parameters.</param>
        public void DeserializeRequest(Message message, object[] parameters)
        {
            formatter.DeserializeRequest(message, parameters);
        }

        /// <summary>
        /// Serializes a reply message from a specified message version, array of parameters, and a return value.
        /// </summary>
        /// <param name="messageVersion">The SOAP message version.</param>
        /// <param name="parameters">The out parameters</param>
        /// <param name="result">The return value.</param>
        /// <returns>The serialized reply message.</returns>
        public Message SerializeReply(MessageVersion messageVersion, Object[] parameters, Object result)
        {
            var message = formatter.SerializeReply(messageVersion, parameters, result);
            return new XmlDeclarationMessage(message);
        } 
    }
}
